package com.example.demo.filter;

import com.example.demo.model.JwtResponse;
import com.example.demo.model.CustomUserDetails;
import com.example.demo.utils.JwtTokenProvider;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AuthCustomSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    JwtTokenProvider tokenProvider;

    @Value("${app.jwtExpirationInMs}")
    private Long jwtExpirationInMs;
    @Value("${app.jwtExpirationRefreshInMs}")
    private Long jwtRefreshExpiration;

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        System.out.println("进入登录成功方法");

        //成功之后，principle对应的完成用户信息
        CustomUserDetails customUserDetails = (CustomUserDetails) authentication.getPrincipal();
        String accessToken = tokenProvider.generatorJwtToken(customUserDetails.getUser().getUsername(), "username", jwtExpirationInMs);
        String refreshToken = tokenProvider.generatorJwtToken(customUserDetails.getUser().getUsername(), "username", jwtRefreshExpiration);

        JwtResponse jwtResponse = new JwtResponse(accessToken, refreshToken);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(new ResponseEntity(jwtResponse, HttpStatus.OK)));
    }
}
